package com.example.authority.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.authority.common.Result;
import com.example.authority.entity.Comment;

import com.example.authority.entity.User;
import com.example.authority.service.CommentService;

import com.example.authority.service.SeekService;
import com.example.authority.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program:
 * @ClassName:CommentController
 * @description: CommentController前端控制器
 *       
 * @Version 3.0
 **/
@Tag(name = "评论管理 前端控制器")
@RestController
@RequestMapping("/comment")
public class CommentController {

        @Resource
        private CommentService commentService;
        @Resource
        private UserService userService;
        @Resource
        private SeekService articleService;

        private static final Logger log = LoggerFactory.getLogger(CommentController.class);

        /**
         * 新增
         *
         * @param comment
         * @return
         */
        @Operation(summary = "新增")
        @PostMapping
        public Result save(@RequestBody Comment comment) {



                return Result.success(commentService.save(comment));
        }

        /**
         * 修改
         *
         * @param comment
         * @return
         */
        @Operation(summary = "修改")
        @PutMapping("/{id}")
        public Result update(@PathVariable Long id, @RequestBody Comment comment) {
                return Result.success(commentService.updateById(comment));
        }

        /**
         * 查询所有Comment
         *
         * @return
         */
        @Operation(summary = "查询所有Comment")
        @GetMapping
        public Result findAll() {
                return Result.success(commentService.list());
        }

        @Operation(summary = "查询对应的评论Comment，实现递归数据结构")
        @GetMapping("/article/{id}")
        public Result findByArti(@PathVariable Long id) {
                List<Comment> commentList = commentService.list(new LambdaQueryWrapper<Comment>().eq(Comment::getSid, id).orderByDesc(Comment::getId));
                List<Comment> comments = new ArrayList<>();
                for (Comment comment : commentList) {
                        User user = userService.getById(comment.getUid());
                        if (ObjectUtil.isNotEmpty(user)) {
                                comment.setUser(user);
                        }
                        for (Comment sonComment : commentList) {
                                if (sonComment.getParentId().equals(comment.getId())) {
                                        comment.getReply().setTotal(comment.getReply().getTotal() + 1);
                                        comment.getReply().getList().add(sonComment);
                                }
                        }
                        if (comment.getParentId() == 0L) {
                                comments.add(comment);
                        }
                }

                return Result.success(comments);
        }

        /**
         * 获取单个
         *
         * @param id
         * @return
         */
        @Operation(summary = "获取单个")
        @GetMapping("/{id}")
        public Result findOne(@PathVariable Integer id) {
                return Result.success(commentService.getById(id));
        }

        /**
         * 分页显示
         *
         * @param name
         * @param pageNum
         * @param pageSize
         * @return
         */
        @Operation(summary = "分页显示")
        @GetMapping("/page")
        public Result findPage(
                @RequestParam(defaultValue = "") String name,
                @RequestParam(defaultValue = "") String sid,
                @RequestParam(defaultValue = "1") Integer pageNum,
                @RequestParam(defaultValue = "10") Integer pageSize) {
                QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
                // 处理评论内容查询
                if (StrUtil.isNotEmpty(name)) {
                    queryWrapper.like("content", name);
                }
                // 处理种子ID查询
                if (StrUtil.isNotEmpty(sid)) {
                    try {
                        Long seedId = Long.parseLong(sid);
                        queryWrapper.eq("sid", seedId);
                    } catch (NumberFormatException e) {
                        // 如果sid不是有效的数字，则忽略这个条件
                        log.warn("Invalid sid format: {}", sid);
                    }
                }
                // 按ID降序排序
                queryWrapper.orderByDesc("id");
                
                // 执行分页查询
                Page<Comment> page = commentService.page(new Page<>(pageNum, pageSize), queryWrapper);
                
                // 为每条评论加载用户信息和种子信息
                List<Comment> records = page.getRecords();
                for (Comment comment : records) {
                    // 加载用户信息
                    User user = userService.getById(comment.getUid());
                    if (ObjectUtil.isNotEmpty(user)) {
                        comment.setUser(user);
                    }
                    // 加载种子信息
                    if (comment.getSid() != null) {
                        comment.setSeek(articleService.getById(comment.getSid()));
                    }
                }
                page.setRecords(records);
                
                return Result.success(page);
        }

        /**
         * 单个删除
         *
         * @param id
         * @return
         */
        @Operation(summary = "单个删除")
        @DeleteMapping("/{id}")
        public Result delete(@PathVariable Integer id) {

                return Result.success(commentService.removeById(id));
        }

        /**
         * 批量删除
         *
         * @param ids
         * @return
         */
        @Operation(summary = "批量删除")
        @DeleteMapping("/batch/{ids}")
        @Transactional
        public Result deleteByIds(@PathVariable String[] ids) {
                return Result.success(commentService.removeByIds(Arrays.asList(ids)));
        }





}